<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-form
          ref="detail"
          :model="detail"
          :rules="editRules"
          class="edit-form"
          autocomplete="on"
          label-position="right"
          label-width="100px"
        >
          <el-form-item prop="categoryId" label="所属栏目">
            <el-input
              v-model="detail.categoryName"
              placeholder="请选择栏目"
              class="width-220 selectTree-input"
              auto-complete="off"
              @click.native="changeSelectTree()"
              @blur="hideParentClick"
            />
            <el-tree
              v-show="isShowSelect"
              id="floatTree"
              ref="selectTree"
              empty-text="暂无数据"
              :highlight-current="true"
              :default-expand-all="true"
              :expand-on-click-node="true"
              :data="categoryList"
              :filter-node-method="filterNode"
              class="width-220 selectTree-input objectTree"
              @node-click="selectClassfy"
            />
          </el-form-item>
          <el-form-item prop="title" label="标题">
            <el-input v-model="detail.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item prop="subtitle" label="副标题">
            <el-input v-model="detail.subtitle" placeholder="请输入副标题" />
          </el-form-item>
          <el-form-item prop="author" label="作者" class="postInfo-container-item">
            <el-input v-model="detail.author" placeholder="请输入作者" />
          </el-form-item>
          <el-form-item prop="abstractContent" label="摘要">
            <el-input v-model="detail.abstractContent" type="textarea" placeholder="请输入摘要" />
          </el-form-item>
          <el-form-item prop="type" label="文章类型">
            <el-select v-model="detail.type" placeholder="请选择">
              <el-option
                v-for="item in articleTypeList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="linkedUrl" label="链接">
            <el-input v-model="detail.linkedUrl" placeholder="请输入链接地址" />
          </el-form-item>
          <el-form-item prop="status" label="发布状态">
            <el-select v-model="detail.status" placeholder="请选择">
              <el-option
                v-for="item in articleStatusList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="publishedTime" label="发布时间">
            <el-date-picker
              v-model="detail.publishedTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请输入发布时间"
            />
          </el-form-item>
          <el-form-item prop="sort" label="同级排序">
            <el-input-number v-model="detail.sort" :min="0" :max="1000" :step="1" label="排序值" />
            （数值大靠前）
          </el-form-item>

          <el-form-item v-if="!detail.id && categoryMap[detail.categoryId] !== 'LOOP'" prop="sort" label="同步到首页">
            <el-switch
              v-model="detail.isSync"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0"
            />
            (是否同步到首页轮播)
          </el-form-item>

          <el-form-item prop="file" label="封面图" label-width="80px">
            <div v-if="detailId === 0">
              <multi-upload-image
                v-model="titleImage"
                :max-count="1"
                :data-obj="{refType: 'articleImg', relativePath: 'article/img'}"
              />
            </div>
            <div v-if="detail.id !== null && titleImage !== null">
              <multi-upload-image
                v-model="titleImage"
                :max-count="1"
                :data-obj="{refType: 'articleImg', relativePath: 'article/img'}"
              />
            </div>
          </el-form-item>
          <el-form-item
            prop="content"
            style="margin-bottom: 30px;"
            label="内容"
          >
            <Tinymce
              ref="editor"
              v-model="detail.content"
              :height="400"
            />
          </el-form-item>
        </el-form>
        <div class="bottom">
          <el-button type="primary" @click="saveArticle">确 定</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { articleCreate, articleStatus, articleTypes, articleUpdate, getArticle } from '@/api/rest/cms/article'
import { categoryList } from '@/api/rest/cms/category'
import { elRequiredRule, elValidateInteger } from '@/utils/el-validator'
import { formatDateTime } from '@/utils/formatdate'
import MultiUploadImage from '@/components/Upload/MultiUploadImage'

export default {
  name: 'ArticleDetail',
  components: {
    Tinymce, MultiUploadImage
  },
  data() {
    return {
      title: '',
      isShowSelect: false,
      detailId: null,
      titleImageShow: false,
      detail: {
        id: null,
        title: null,
        subtitle: null,
        author: null,
        company: null,
        linkedUrl: null,
        titleImageId: 0,
        attachId: 0,
        abstractContent: null,
        content: null,
        categoryId: null,
        categoryName: null,
        type: 0,
        status: 0,
        publishedTime: null,
        sort: 0,
        visitCount: 0,
        isSync: 0
      },
      // titleImage: [],
      imgFileList: null,
      attachFileList: [],
      deleteAttachmentIds: [],
      articleStatusList: [],
      articleTypeList: [],
      categoryList: [],
      categoryMap: {},
      editRules: {
        title: elRequiredRule,
        categoryId: elRequiredRule,
        sort: [{ trigger: 'change', validator: elValidateInteger }],
        type: elRequiredRule
      },
      baseApi: process.env.VUE_APP_BASE_API
    }
  },
  computed: {
    titleImage: {
      get: function() {
        if (this.detail.titleImageId === 0) {
          return []
        }
        return [this.detail.titleImageId]
      },
      set: function(newValue) {
        if (newValue == null || newValue.length === 0) {
          this.detail.titleImageId = 0
        } else {
          this.detail.titleImageId = newValue[0]
        }
      }
    }
  },
  watch: {
    $route(to, from) {
      this.detailId = this.$route.query.detailId || 0
      this.getArticle()
    }
  },
  created() {
    this.detailId = this.$route.query.detailId || 0
    articleStatus().then(response => {
      this.articleStatusList = response.data
    })
    articleTypes().then(response => {
      this.articleTypeList = response.data
    })
    this.getArticle()
    this.getCategoryList()
  },
  methods: {
    getCategoryList() {
      categoryList(this.listQuery).then(response => {
        this.categoryList = response.data
        this.categoryMap = this.disposeCategoryMap(this.categoryList)
      })
    },
    getArticle() {
      const that = this
      if (that.detailId) {
        getArticle(that.detailId).then(response => {
          if (response.code === 0) {
            const detail = response.data
            if (detail.publishedTime) {
              detail.publishedTime = formatDateTime(detail.publishedTime)
            }
            that.detail = detail
            that.titleImage = detail.titleImageId ? [detail.titleImageId] : []
          }
        })
      }
    },
    selectClassfy(data) {
      this.detail.categoryName = data.label
      this.detail.categoryId = data.id
      this.isShowSelect = false
    },
    changeSelectTree() {
      if (!this.detail.categoryId || this.detail.categoryId !== 0) {
        this.isShowSelect = true
      }
    },
    hideParentClick(e) {
      const isOther = e.relatedTarget == null || e.relatedTarget.closest('div.el-tree') == null || e.relatedTarget.closest('div.el-tree').id !== 'floatTree'
      if (isOther) {
        this.isShowSelect = false
      } else {
        e.target.focus()
      }
    },
    // 选择器的树节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    saveArticle() {
      const that = this
      that.$refs.detail.validate(valid => {
        if (valid) {
          if (that.detail.id) {
            articleUpdate(that.detail).then(response => {
              if (response.code === 0) {
                that.$message({
                  type: 'success',
                  message: '修改文章成功'
                })
                that.$store.state.tagsView.visitedViews.splice(that.$store.state.tagsView.visitedViews.findIndex(item => item.path === that.$route.path), 1)
                that.$router.push(that.$store.state.tagsView.visitedViews[that.$store.state.tagsView.visitedViews.length - 1].path)
              }
            })
          } else {
            articleCreate(that.detail).then(response => {
              if (response.code === 0) {
                that.$message({
                  type: 'success',
                  message: '添加文章成功'
                })
                that.$store.state.tagsView.visitedViews.splice(that.$store.state.tagsView.visitedViews.findIndex(item => item.path === that.$route.path), 1)
                that.$router.push(that.$store.state.tagsView.visitedViews[that.$store.state.tagsView.visitedViews.length - 1].path)
              }
            })
          }
        }
      })
    },
    disposeCategoryMap(list) {
      const map = {}
      list.forEach(item => {
        map[item.id] = item.code
        if (item.children && item.children.length > 0) {
          Object.assign(map, this.disposeCategoryMap(item.children))
        }
      })

      return map
    }
  }
}
</script>
<style scoped>
.buttons {
  margin-top: 10px;
}

/*下拉框选择树*/
.objectTree {
  margin-left: 0px;
  position: absolute;
  overflow: auto;
  z-index: 100;
  height: 200px;
  border: 1px solid #ddd;
  line-height: normal;
  z-index: 204;
}

.width-220 {
  width: 220px
}
</style>

